var types;
$().ready(function() {
	validateRule();

    // 模块隐藏
    $("#topicTypes").change(function (val){
        types = val.target.value;
        if(val.target.value == '4' || val.target.value == '5' || val.target.value == '6'){
            $("#typesId").hide()
        }else{
            $("#typesId").show()
        }
    })


});
layui.use(['upload'], function () {
    var upload = layui.upload;
    var fileLinks = [];  // 用于保存文件链接的数组
    upload.render({
        elem: '#btnUpload',
        url: '/common/sysFile/upload',
        timeout: 36000000,
        multiple:true, // 开启多文件上传
        // size: 1024 * 100,
        accept: 'file',
        // exts: 'docx|doc|xlsx|pdf|ppt',
        done: function (r) {
            let type = $('#topicTypes').val()
            // 根据条件判断是否阻止上传请求
            if(type === ''){
              return parent.layer.msg("请选择题目类型");
            }
            if( type === '4' || type === '6') {
                fileLinks.push(r.data);  // 将文件链接保存到数组中
                $("#testArr").append(subFileName(r.data));
                return
            }

            $("#fileRoute").val(r.data);
            $("#test").html(subFileName(r.data));
        },
        allDone: function(){
            // 所有文件上传完毕后触发的回调函数
            $('#resourceUrlArr').val(fileLinks)
        },
        error: function (r) {
            layer.msg(r.msg);
        }
    });
});

$.validator.setDefaults({
	submitHandler : function() {
		save();
	}
});

$(function () {
    $("#resourceType").change(function () {
        $("#enclosure").val("");
        $("#test").html("");
        var type = $(this).val();
        if (type!=0&&type!='') {
            $("#resourse").show();
            $("#btnUpload").show()
        } else {
            $("#resourse").hide();
        }
    });
});

//证书选择
$("#profileId").change(function () {
    $("#kpointsId").empty();
    $("#know").html("");
    $.ajax({
        url: '/jzweb/itemBank/byKnowledges',
        data :{cprofileId:$(this).val()} ,
        success: function (r) {
            if(r.data.length==0){
                $("#kpointsId").append('<option value="">暂无数据</option>');
            }else{
                $("#kpointsId").append('<option value="">请选择</option>');
                for(var p in r.data){
                    $("#kpointsId").append('<option value="'+r.data[p].id+'">'+r.data[p].name+'</option>');
                }
            }

        }
    })
});

//知识点选择
$("#kpointsId").change(function () {
    $.ajax({
        url: '/jzweb/itemBank/byGrades',
        data :{knowId:$(this).val()} ,
        success: function (r) {
            var gradeList = r.data.split(",");
            var list ='';
            if(r.data.length==0){
                list+='暂无数据';
            }else{
                for(var p in gradeList){
                    list+='<span><input name="grade" type="checkbox" value="'+gradeList[p]+'"/>'+gradeList[p]+'</span>';
                }
            }
            list+='</select>';
            $("#know").html(list);
        }
    })
});

function save() {
    let type = $('#topicTypes').val()
    var formData = $('#signupForm').serializeArray();
    //数据处理
    if( types == '4' ){
        $("#typesId").remove();
    }
    let dataJson = {}
    if(type === '4' || type === '5' || type === '6') {
        let list = $('#resourceUrlArr').val().split(',')
        let a = []
        for (let i = 0; i < formData.length; i++) {
            if(formData[i].name === "resourceUrlArr") {
                formData[i].value = list
            }
            if(formData[i].name ==='grade') {
                a.push(formData[i].value)
                formData[i].value = a.join()
            }
        }
    }

    for (let [key, list] of formData.entries()) {
        dataJson[list.name]=  list.value ;
    }

    dataJson['resourceUrlArr'] === '' ? dataJson['resourceUrlArr'] = [] : ''
    addJson(dataJson)


}

function addJson(value) {
    // 添加文件链接数组到表单数据中
    $.ajax({
    	cache : true,
    	type : "POST",
    	url : "/jzweb/itemBank/save",
        headers: { 'Content-Type': 'application/json;charset=UTF-8' },
    	// data : $('#signupForm').serialize(),// 你的formid
        data: JSON.stringify(value),
    	async : false,
    	error : function(request) {
    		parent.layer.alert("Connection error");
    	},
    	success : function(data) {
    		if (data.code == 0) {
    			parent.layer.msg("操作成功");
    			parent.reLoad();
    			var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
    			parent.layer.close(index);

    		} else {
    			parent.layer.alert(data.msg)
    		}

    	}
    });
}
function validateRule() {
	var icon = "<i class='fa fa-times-circle'></i> ";
	$("#signupForm").validate({
		rules : {
            kpointsId : {
				required : true
			},
            profileId : {
                required : true
            },
            itemBankType : {
                required : true
            },
            topicTypes : {
                required : true
            },
            topicContent : {
                required : true
            },
            topicAnalysis : {
                required : true
            },
            score : {
                required : true
            },
            grade : {
                required : true
            }
		},
		messages : {
            kpointsId : {
				required : icon + "请选择知识点"
			},
            profileId : {
                required : icon + "请选择证书概况"
            },
            itemBankType : {
                required : icon + "请选择题库类型"
            },
            topicTypes : {
                required : icon + "请选择题目类型"
            },
            topicContent : {
                required : icon + "请输入题目内容名"
            },
            topicAnalysis : {
                required : icon + "请输入题目解析"
            },
            score : {
                required : icon + "请输入分值"
            }
		}
	})
}